import React, { useState } from "react";
import { Modal, Form, Input, Row, Col, Space, AutoComplete, InputNumber, Button, DatePicker, Select } from "antd";
import { companyTypes, modalPropsType } from "@/constants/types";
import XlSelect from "@/components/Form/XlSelect";
import { useModel } from "@umijs/max";
import { useComponentDidMount } from "@/hooks";
import { fetchCustomerOptions, fetchOrderOptions } from "@/pages/OrderManage/services";

const {Item} = Form;
const labelCol = {span: 3};
const rules = [{required: true}];
const initValues = {
  feeItems: [{}]
}

const MakeUpBill = ({title, onCancel, onSubmit, visible}: modalPropsType) => {
  const [form] = Form.useForm();
  const { getDict } = useModel("dictModel");
  const feeItems = getDict("feeItem");

  const customerCode = Form.useWatch("customerCode", form);
  const [orderCodes, setOrderCodes] = useState<any []>([]);


  const [companyList, setCompanyList] = useState<companyTypes []>([]);

  const handleSubmit =async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      payTime: res?.payTime?.format("YYYY-MM-DD 23:59:59"),
      customerName: companyList?.find((v: companyTypes) => v?.value === res?.customerCode)?.label,
      feeItems: res?.feeItems?.map((v: any) => ({
        ...v,
        feeName: feeItems?.find((fee: any) => fee?.value === v?.feeCode)?.label
      }))
    });
  }

  const handleSearch = (text: string) => {
    if (!text || text.length < 5 || !customerCode) {
      setOrderCodes([]);
      return;
    }
    fetchOrderOptions({
      orderCode: text,
      customerCode
    }).then(
      res => {
        setOrderCodes((res || [])?.map((v: any) => ({label: v?.orderCode, value: v?.orderCode})));
      }
    )
  }

  useComponentDidMount(() => {
    fetchCustomerOptions({customerName: ""}).then(
      res => {
        setCompanyList((res || []).map((v: any) => ({
          ...v,
          label: v?.nickName,
          value: v?.code
        })));
      }
    )
  });

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      maskClosable={false}
      onOk={handleSubmit}
      width="750px"
    >
      <Form form={form} labelCol={labelCol} initialValues={initValues} className="modal-form-padding">
        <Item label="公司简称" rules={rules} name="customerCode">
          <XlSelect allowClear showSearch optionFilterProp="label" options={companyList} />
        </Item>
        <Item label="订单号" rules={rules} name="orderCode">
          <Select
            showSearch
            options={orderCodes}
            filterOption={false}
            onSearch={handleSearch}
          />
        </Item>
        <Item label="付款时间" rules={rules} name="payTime">
          <DatePicker style={{width: 613}} />
        </Item>
        <Form.List name="feeItems">
          {(fields, {add, remove}) =>
            fields.map((field) => (
              <Row key={field.name}>
                <Col span={8}>
                  <Form.Item label="费用项" name={[field.name, 'feeCode']} labelCol={{span: 9}} rules={rules}>
                    <XlSelect showSearch optionFilterProp="label" allowClear options={feeItems} style={{width: 180}} />
                  </Form.Item>
                </Col>
                <Col span={11}>
                  <Form.Item label="金额/元" name={[field.name, 'amount']} labelCol={{span: 9}} rules={rules}>
                    <InputNumber min={0} style={{width: 180}} />
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Space>
                    <Button type="link" onClick={() => add()}>新增</Button>
                    <Button type="link" onClick={() => remove(field.name)}>删除</Button>
                  </Space>
                </Col>
              </Row>
            ))
          }
        </Form.List>
        <Item label="备注" name="remark">
          <Input.TextArea rows={3} />
        </Item>
      </Form>
    </Modal>
  );
}
export default MakeUpBill;